<?php

namespace app\base\logic;

use app\base\model\logs\SmsSendLogsModel;

use app\base\model\setting\SettingSmsModel;

use app\common\helper\sms\SmsHelper;

use app\common\model\AppModel;

use app\common\model\ShopModel;

use app\common\model\SmsTplModel;



class SmsInitLogic{

    public function send($shop_id,array $mobiles,$params,$key)

    {

        $shop = ShopModel::find($shop_id);

        if(null === $shop) return false;



        //获取短信设置

        $sms_setting = SettingSmsModel::where([['shop_id','=',$shop_id]])->find();

        if(null === $sms_setting) return false;



        //判断短信剩余条数

        $sms_num =  $sms_setting ->sms_num;

        if(count($mobiles) > $sms_num) return false;



        //获取sms_id

        $sms_tpl=SmsTplModel::where([

            ['key','=',$key],

            ['is_delete','=',0]

        ])->find();

        if($sms_tpl === null) return false;

        $sms_id=$sms_tpl->sms_id;

        $params['shop_id'] = $shop_id; //后期增加短信小程序url跳转用

        //发送短信

        $SmsHelper = new SmsHelper();

        $SmsHelper->sendNotice($sms_id,$mobiles,$params);



        $sms_setting->sms_num = $sms_num-count($mobiles);

        $sms_setting->save();



        //添加日志

        $send_data=[];

        foreach ($mobiles as $mobile){

            $send_data[]=[

                'shop_id'=>$shop_id,

                'mobile'=>$mobile,

                'send_type'=>$sms_tpl->effect,

                'after_sms_num'=>$sms_setting->sms_num,

            ];

        }

        $sms_send_model = new SmsSendLogsModel();

        $sms_send_model->saveAll($send_data);

        return true;



    }



}

